package com.servicelive.service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.hibernate.Query;
import org.hibernate.Session;

import com.servicelivedb.ServiceliveDB;
import com.servicelivedb.data.Block;
import com.servicelivedb.data.Customer;
import com.servicelivedb.data.Door;
import com.servicelivedb.data.Items;
import com.servicelivedb.data.Order;
import com.servicelivedb.data.OrderItems;
import com.wavemaker.runtime.RuntimeAccess;
import com.wavemaker.runtime.javaservice.JavaServiceSuperClass;
import com.wavemaker.runtime.service.annotations.ExposeToClient;

/**
 * This is a client-facing service class. All public methods will be exposed to
 * the client. Their return values and parameters will be passed to the client
 * or taken from the client, respectively. This will be a singleton instance,
 * shared between all requests.
 * 
 * To log, call the superclass method log(LOG_LEVEL, String) or log(LOG_LEVEL,
 * String, Exception). LOG_LEVEL is one of FATAL, ERROR, WARN, INFO and DEBUG to
 * modify your log level. For info on these levels, look for tomcat/log4j
 * documentation
 */
@ExposeToClient
public class MailSenderService extends JavaServiceSuperClass {
	/*
	 * Pass in one of FATAL, ERROR, WARN, INFO and DEBUG to modify your log
	 * level; recommend changing this to FATAL or ERROR before deploying. For
	 * info on these levels, look for tomcat/log4j documentation
	 */
	public MailSenderService() {
		super(INFO);
	}

	// Change these parameters to use your own email service!
	private String smtpHost;
	private String smtpHostUser;
	private String smtpHostPassword;
	private String senderEmail;
	private String smtpPort;

	/*
	 * Pass in one of FATAL, ERROR, WARN, INFO and DEBUG to modify your log
	 * level; recommend changing this to FATAL or ERROR before deploying. For
	 * info on these levels, look for tomcat/log4j documentation
	 */

	public String sendEmail(String fromEmailAddress, String toEmailAddress,
			String emailSubject, String emailMessage) {
		try {

			// Use javamail api, set parameters from registration.properties
			// file
			// set the session properties
			Properties props = System.getProperties();
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.host", smtpHost);
			props.put("mail.smtp.port", smtpPort);
			props.put("mail.smtp.auth", "true");

			props.put("mail.smtp.starttls.required", "true");
			javax.mail.Session mailSession = javax.mail.Session
					.getDefaultInstance(props, null);
			System.out.println("Send email:Sessio established:" + mailSession);
			// Create email message
			MimeMessage message = new MimeMessage(mailSession);
			message.setFrom(new InternetAddress(senderEmail));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
					toEmailAddress));
			message.setSubject(emailSubject);
			message.setText(emailMessage);

			// Send smtp message
			Transport tr = mailSession.getTransport("smtp");
			tr.connect(smtpHost, new Integer(smtpPort), smtpHostUser,
					smtpHostPassword);
			// message.saveChanges();
			System.out.println("Send smtp message:");

			tr.sendMessage(message, message.getAllRecipients());
			tr.close();
			System.out.println("Message sent successfully");

			return "Mail sent successfully.";

		} catch (MessagingException e) {
			log(ERROR, "Error in method sendEmailNotification: ", e);
			return "Error in method sendEmailNotification: " + e;
		}
	}

	public String sendEmailToVendor(String orderId) {
		ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");

		try {
			db.begin();
			System.out.println("orderId : " + orderId);
			Session session = db.getDataServiceManager().getSession();
			Order order = (Order) session.get(Order.class,
					Integer.parseInt(orderId));

			Customer vendor = order.getCustomerByVendorId();
			Customer customer = order.getCustomerByCustomerId();

			Block block = customer.getBlock();
			Door door = customer.getDoor();

			Query query = session
					.createQuery(" from OrderItems orderItems where orderItems.order.orderId= :orderId");
			query.setBigInteger("orderId",
					BigInteger.valueOf(Integer.parseInt(orderId)));

			List orderList = query.list();
			StringBuilder itemDetails = new StringBuilder();
			BigDecimal totalPrice = new BigDecimal(0);

			itemDetails
					.append("<table ><tr><td>Item Name </td> <td> Description </td> <td> Quantity</td> <td> Rate </td> <td> Total </td></tr>");

			for (int index = 0; index < orderList.size(); index++) {
				OrderItems orderItem = (OrderItems) orderList.get(index);
				Items item = orderItem.getItems();
				itemDetails.append("<tr>");
				itemDetails.append("<td>");
				itemDetails.append(item.getItemName());
				itemDetails.append("</td>");

				itemDetails.append("<td>");
				itemDetails.append(item.getItemDesc());
				itemDetails.append("</td>");

				itemDetails.append("<td>");
				itemDetails.append(item.getQuantity() + item.getUnit());
				itemDetails.append("</td>");

				itemDetails.append("<td>");
				itemDetails.append(item.getPrice() + item.getCurrency());
				itemDetails.append("</td>");

				itemDetails.append("<td>");
				itemDetails.append(orderItem.getPrice() + item.getCurrency());
				itemDetails.append("</td>");

				itemDetails.append("</tr>");
			}

			itemDetails.append("<br><br> Total Price : Rs. " + order.getTotalPrice());

			// Use javamail api, set parameters from registration.properties
			// file
			// set the session properties
			Properties props = System.getProperties();
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.host", smtpHost);
			props.put("mail.smtp.port", smtpPort);
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.starttls.required", "true");
			javax.mail.Session mailSession = javax.mail.Session
					.getDefaultInstance(props, null);

			// Send smtp message
			Transport tr = mailSession.getTransport("smtp");
			tr.connect(smtpHost, new Integer(smtpPort), smtpHostUser,
					smtpHostPassword);

			String vendorEmailSubject = "H2MApp: Order#" + order.getOrderId();
			String vendorEmailMessage = "<b> You have got a new order. <br><br> <u> Order Details : </u> <br> Customer Name : "
					+ customer.getName()
					+ "<br> Order# :"
					+ orderId
					+ "<br> Address : "
					+ order.getAddress()
					+ "<br> Contact Number : "
					+ customer.getPrimaryPhone()
					+ "<br> <br> <b><u> Order Details </b></u>"
					+ "<br>"
					+ itemDetails
					+ "<br> <br> <br> Regards "
					+ "�2014 H2MAPP.COM . All right reserved. ";

			// Create email message
			MimeMessage messageVendor = new MimeMessage(mailSession);
			messageVendor.setFrom(new InternetAddress(senderEmail));
			messageVendor.addRecipient(Message.RecipientType.TO,
					new InternetAddress(vendor.getEmail()));
			messageVendor.addRecipient(Message.RecipientType.CC,
					new InternetAddress("nykupr@gmail.com"));
			messageVendor.addRecipient(Message.RecipientType.CC,
					new InternetAddress("h2mappsupport@technologyport.net"));
			messageVendor.setSubject(vendorEmailSubject);

			String mailFormat = GetMail();
			vendorEmailMessage = mailFormat.replace("@ActuallMessage@",
					vendorEmailMessage);

			messageVendor.setContent(vendorEmailMessage, "text/html");
			messageVendor.saveChanges();

			System.out
					.println("Sending mail to Vendor  : " + vendor.getEmail());
			tr.sendMessage(messageVendor, messageVendor.getAllRecipients());

			String customerEmailSubject = "H2MApp: Order Placed#"
					+ order.getOrderId();
			String customerEmailMessage = "Dear "
					+ customer.getName()
					+ ",<br> Greetings from H2MAPP.COM team ! <br>Your order has been placed successfully!."
					+ "<br>Your Order # is "
					+ orderId
					+ " Order Date:"
					+ order.getOrderDt()
					+ "br> <u> Order Details </b></u>"
					+ "<br>"
					+ itemDetails
					+ "<br> Vendor will supply requested goods/ service and get back to you shortly if any clarification.  <br>"
					+ "Thank you  for choosing NGVAPP<br>"
					+ "@2014 H2MAPP.COM . All right reserved. ";

			customerEmailMessage = mailFormat.replace("@ActuallMessage@",
					customerEmailMessage);
			MimeMessage messageCustomer = new MimeMessage(mailSession);
			messageCustomer.setFrom(new InternetAddress(senderEmail));
			messageCustomer.addRecipient(Message.RecipientType.TO,
					new InternetAddress(customer.getEmail()));
			messageCustomer.setSubject(customerEmailSubject);
			messageCustomer.setContent(customerEmailMessage, "text/html");

			messageCustomer.saveChanges();

			System.out.println("Sending mail to customer  : "
					+ customer.getEmail());
			tr.sendMessage(messageCustomer, messageCustomer.getAllRecipients());

			tr.close();
			db.commit();
			return "Mail sent successfully.";

		} catch (MessagingException e) {
			db.rollback();
			log(ERROR, "Error in method sendEmailNotification: ", e);
			return "Error in method sendEmailNotification: " + e;
		}
	}

	public void SendSms() {

		String endPoint = "http://bulksms.mysmsmantra.com:8080/WebSMS/SMSAPI.jsp?username=adisagar&password=1262006954&sendername=adisagar&mobileno=8095504222&message=Hello";
		// GetMethod get = new GetMethod("http://httpcomponents.apache.org");
		// execute method and handle any error responses.
		// ...
		// InputStream in = get.getResponseBodyAsStream();
		// Process the data from the input stream.
		// get.releaseConnection();

	}

	public String GetMail() {
		String mail = " <html>  <head>     <title>     </title>    <meta content=\"width=device-width; initial-scale=1.0; maximum-scale=1.0;\" name=\"viewport\" />     <meta content=\"text/html; charset=UTF-8\" http-equiv=\"Content-Type\" />   </head>   <body style=\"margin:0;padding:0\">     <table border=\"0\" cellpadding=\"40\" cellspacing=\"0\" class=\"wrapper-table\" style=\"width:100%;background-color:#6192e8\">       <tbody>         <tr class=\"wrapper-table-tr\">           <td class=\"wrapper-table-td\" style=\"width:100%;text-align:center;background-color:#6192e8\">             <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"container-table\" style=\"background-color:#ffffff;border:5px solid #16469a;width:500px;margin:0 auto\">               <tbody>                 <tr class=\"container-table-tr\">                   <td class=\"container-table-td\" style=\"width:500px;text-align:left;background-color:#ffffff\">                     <table border=\"0\" cellpadding=\"20\" cellspacing=\"0\" class=\"padding-table\" style=\"width:100%;background-color:#ffffff;border:0\">                       <tbody>                         <tr>                           <td class=\"padding-table-td\" style=\"width:100%;text-align:left;background-color:#ffffff\">                             <img alt=\"\" src=\"E:\\Projects\\WaveMaker\\projects\\projects\\h2m\\webapproot\\resources\\images\\logos\\h2m.png\" style=\"width: 300px; height: 60px;\" />                             <hr style=\"height:1px;border:none;background-color:#16469a;margin-top:20px\" />                           </td>                         </tr>                       </tbody>                     </table>                   </td>                 </tr>                 <tr class=\"container-table-tr\">                   <td class=\"container-table-td\" repeater=\"true\" style=\"width:500px;text-align:left;background-color:#ffffff\">                     <div layout=\"true\" layout-label=\"Paragraph with header\" repeater-id=\"0\">                       <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">                         <tbody>                           <tr class=\"container-table-tr\">                             <td class=\"container-table-td\" style=\"width:500px;text-align:left;background-color:#ffffff\">                               <table border=\"0\" cellpadding=\"10\" cellspacing=\"0\" class=\"padding-table\" style=\"width:100%;background-color:#ffffff;border:0\">                                 <tbody>                                   <tr class=\"padding-table-tr\">                                     <td class=\"padding-table-td\" style=\"width:100%;text-align:left;background-color:#ffffff\">                                       <h1 style=\"padding:0 20px;margin:0 0 20px 0;color:#e861d6;font-family:Arial,sans-serif;font-size:22px;font-weight:normal\">                                         Welcome to H2M NGV!!                                       </h1>                                       <p style=\"color:#000000;padding:0 20px;margin:0 0 20px 0;font-family:Arial,sans-serif;font-size:14px;font-weight:normal;line-height:21px\">                                         Thanks for choosing H2M! <br> @ActuallMessage@      </p>                                     </td>                                   </tr>                                 </tbody>                               </table>                             </td>                           </tr>                         </tbody>                       </table>                     </div>                   </td>                 </tr>                 <tr class=\"container-table-tr\">                   <td class=\"container-table-td\" style=\"width:500px;text-align:left;background-color:#ffffff\">                     <table border=\"0\" cellpadding=\"10\" cellspacing=\"0\" class=\"padding-table\" style=\"width:100%;background-color:#ffffff;border:0\">                       <tbody>                         <tr class=\"padding-table-tr\">                           <td class=\"padding-table-td footer-td\" style=\"width:100%;text-align:left;background-color:#16469a\">                             <p style=\"color:#ffffff;padding:0;margin:0;font-family:Arial,sans-serif;font-size:11px;font-weight:normal;line-height:18px\">                               Copyright(c) 2013 H2M. All Rights Reserved.                             </p>                           </td>                         </tr>                       </tbody>                     </table>                   </td>                 </tr>               </tbody>             </table>   </td>         </tr>       </tbody>     </table>   </body> </html>";

		return mail;

	}

	public String sendPasswordinEmail(String email) throws Exception {
		ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");

		try {
			db.begin();

			Session session = db.getDataServiceManager().getSession();

			Query query = session
					.createQuery(" from Customer customer where customer.email= :email");
			query.setString("email", email);

			List customers = query.list();
			if (customers != null && customers.size() > 0) {
				Customer customer = (Customer) customers.get(0);
				sendEmailToUser("noreply_h2m@gmail.com", customer.getEmail(),
						"Password Reset",
						"Your password is " + customer.getPassword());

			} else {
				return "Email not found in the system,Please check.";
			}

			db.commit();
			return "Password has been sent to your email Id.";
		} catch (Exception exp) {
			db.rollback();
			log(ERROR, "Error in method sendEmailNotification: ", exp);
			return "Error during password reset.";
		}

	}

	public String sendEmailToUser(String fromEmailAddress,
			String toEmailAddress, String emailSubject, String emailMessage)
			throws Exception {
		Transport tr = null;
		try {

			// Use javamail api, set parameters from registration.properties
			// file
			// set the session properties
			Properties props = System.getProperties();
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.host", smtpHost);
			props.put("mail.smtp.port", smtpPort);
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.starttls.required", "true");
			javax.mail.Session mailSession = javax.mail.Session
					.getDefaultInstance(props, null);

			// Create email message
			MimeMessage message = new MimeMessage(mailSession);
			message.setFrom(new InternetAddress(senderEmail));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
					toEmailAddress));
			message.setSubject(emailSubject);
			message.setText(emailMessage);

			// Send smtp message
			tr = mailSession.getTransport("smtp");
			tr.connect(smtpHost, new Integer(smtpPort), smtpHostUser,
					smtpHostPassword);
			// message.saveChanges();
			tr.sendMessage(message, message.getAllRecipients());
			tr.close();

			return "Mail sent successfully.";

		} catch (MessagingException e) {
			log(ERROR, "Error in method sendEmailNotification: ", e);
			throw e;
		} finally {
			if (tr != null) {
				try {
					tr.close();
				} catch (MessagingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public String getSmtpHost() {
		return smtpHost;
	}

	public void setSmtpHost(String smtpHost) {
		this.smtpHost = smtpHost;
	}

	public String getSmtpHostUser() {
		return smtpHostUser;
	}

	public void setSmtpHostUser(String smtpHostUser) {
		this.smtpHostUser = smtpHostUser;
	}

	public String getSmtpHostPassword() {
		return smtpHostPassword;
	}

	public void setSmtpHostPassword(String smtpHostPassword) {
		this.smtpHostPassword = smtpHostPassword;
	}

	public String getSenderEmail() {
		return senderEmail;
	}

	public void setSenderEmail(String senderEmail) {
		this.senderEmail = senderEmail;
	}

	public String getSmtpPort() {
		return smtpPort;
	}

	public void setSmtpPort(String smtpPort) {
		this.smtpPort = smtpPort;
	}

}